const router = require("koa-router")();
const notice = require('../../models/Notice/notice.js');
const noticeRece = require('../../models/Notice/noticeRece.js')
const base = require('../../models/Fjxx.js')
router.prefix('/sys/notice')

//获取所有学校通知列表
router.get('/getNoticelist', async (ctx, next) => {
    // let classno=ctx.query.classno
    try {
        let result = await notice.GetByAggregate([
            {
                $addFields: {
                    datetime: {
                        $toDate: "$_id"
                    },
                    signstatus: ""
                }
            },
            {
                $sort: {
                    _id: -1
                }
            }
        ])
        ctx.body = { 'error': false, result: result }
    } catch (err) {
        throw new Error("获取学校通知时出错:[" + err + "]")
    }
})

//获取所有接收通知学生
router.post('/getAllReceStu', async (ctx, next) => {
    let condition = ctx.request.body.condition;
    try {
        // let result = await base.myFindByQuery(
        //     condition,
        //     { "username": 1, "_id": 1 }
        // )
        let result = await base.myAggregate(
            condition
        )
        ctx.body = { 'error': false, result: result }
    } catch (err) {
        throw new Error("获取所有接收通知学生:[" + err + "]")
    }
})

//发送通知给指定学生(向noticeRece库插入数据)
router.post("/sendnotice", async (ctx, next) => {
    let multiData = ctx.request.body.multiData;
    let noticeid=multiData[0].noticeid
    try {
        let result = await noticeRece.insertManyDoc(multiData)
        //微信客户端发送模板消息
        // let accountidlist=[];
        // result.forEach(item => {
        //     accountidlist.push(item.accountid)
        // })
        // let userwxopenid=await base.myFindByQuery({"_id" : { $in : accountidlist}},{"wxopenid":1})
        // let templateMsg={
        //     id:null,
        //     url:"",
        //     data:{
        //         first:{
        //             value:"",
        //             color:""
        //         },
        //         keyword1:{
        //             value:"",
        //             color:""
        //         },
        //         keyword2:{
        //             value:"",
        //             color:""
        //         },
        //         remark:{
        //             value:"",
        //             color:""
        //         },
        //     }
        // };
        // templateMsg.id="WmoU74VQ6y4sgJ9i8XIwfln-cMYB7ZuR-IUVP8RXor4"
        // templateMsg.url=""
        // userwxopenid.forEach(async (item)=>{
        //     templateMsg.data.first.value="测试模拟消息标题"
        //     templateMsg.data.keyword1.value="不用理这个消息，我在测试"
        //     templateMsg.data.keyword2.value="不用理这个消息，我在测试"
        //     templateMsg.data.remark.value="不用理这个消息，我在测试"
        //     try {
        //         let res = await ctx.state.wechatApi.sendTemplate(item.wxopenid, templateMsg.id, templateMsg.url, "#173177", templateMsg.data)          
        //         console.log("完成发送：" + res.msgid)
        //         await noticeRece.UpdateStatus(item._id,noticeid,ctx.state.noticeStatus.get("receTrue"))
        //     } catch (err) {
        //         console.log(err.message)
        //         await noticeRece.UpdateStatus(item._id,noticeid,ctx.state.noticeStatus.get("receFalse"))
        //         // output+=err.message+"\n\r"
        //     }
        // })
        ctx.body = { 'error': false, result: result }
    } catch (err) {
        throw new Error("获取所有接收通知学生:[" + err + "]")
    }
})

//获取通知的签收情况
router.post('/getSignStatus', async (ctx, next) => {
    let noticeid = ctx.request.body.noticeid;
    try {
        let signstatus = await noticeRece.countByAggregate([
            {
                $match: {
                    "noticeid": noticeid
                }
            },
            {
                $group: {
                    _id: {
                        $eq: ["$status", ctx.state.noticeStatus.get("sign")]
                    },
                    count: {
                        $sum: 1
                    }
                }
            }
        ])
        switch (signstatus.length) {
            case 1:
                if (signstatus[0]._id) {
                    ctx.body = { 'error': false, result: [signstatus[0].count, 0] }
                } else {
                    ctx.body = { 'error': false, result: [0, signstatus[0].count] }
                }
                break;
            case 2:
                if (signstatus[0]._id) {
                    ctx.body = { 'error': false, result: [signstatus[0].count, signstatus[1].count] }
                } else {
                    ctx.body = { 'error': false, result: [signstatus[1].count, signstatus[0].count] }
                }
                break;
            default:
                ctx.body = { 'error': false, result: [0, 0] }
                break;
        }
    } catch (err) {
        throw new Error("获取通知计数时出错:[" + err + "]")
    }
})

//按班级获取通知签收情况计数
router.post('/getSignStatusByClass', async (ctx, next) => {
    let noticeid = ctx.request.body.noticeid;
    let classno = ctx.request.body.classno;

    try {
        let signstatus = await noticeRece.countByAggregate([
            {
                $match: {
                    "noticeid": noticeid
                }
            },
            {
                $addFields: {
                    accountid2: {
                        $toObjectId: "$accountid"
                    },

                }
            },
            {
                $lookup: {
                    from: "baseExtendInfo",
                    let: {
                        "accountid3": "$accountid2"
                    },
                    pipeline: [
                        {
                            $match: {
                                "$expr": {
                                    $and: [
                                        {
                                            $eq: [
                                                "$$accountid3",
                                                "$baseid"
                                            ]
                                        },

                                    ]
                                }
                            }
                        },
                        {
                            $project: {
                                "stuname": "$学生姓名",
                                "grade": "$年级",
                                "classno": "$班级",
                                "_id": 0
                            }
                        }
                    ],
                    as: "baseExtendInfo"
                }
            },
            {
                $match: {
                    "baseExtendInfo.classno": classno
                }
            },
            {
                $group: {
                    _id: {
                        $eq: ["$status", ctx.state.noticeStatus.get("sign")]
                    },
                    count: {
                        $sum: 1
                    }
                }
            }
        ])
        switch (signstatus.length) {
            case 1:
                if (signstatus[0]._id) {
                    ctx.body = { 'error': false, result: [signstatus[0].count, 0] }
                } else {
                    ctx.body = { 'error': false, result: [0, signstatus[0].count] }
                }
                break;
            case 2:
                if (signstatus[0]._id) {
                    ctx.body = { 'error': false, result: [signstatus[0].count, signstatus[1].count] }
                } else {
                    ctx.body = { 'error': false, result: [signstatus[1].count, signstatus[0].count] }
                }
                break;
            default:
                ctx.body = { 'error': false, result: [0, 0] }
                break;
        }
    } catch (err) {
        throw new Error("获取通知计数时出错:[" + err + "]")
    }
})

//按班级获取通知签收情况带人员
router.post('/getSignStatusForStu', async (ctx, next) => {
    let noticeid = ctx.request.body.noticeid;
    let classno = ctx.request.body.classno;

    try {
        let signstatus = await noticeRece.countByAggregate([
            {
                $match: {
                    "noticeid": noticeid
                }
            },
            {
                $addFields: {
                    accountid2: {
                        $toObjectId: "$accountid"
                    },

                }
            },
            {
                $lookup: {
                    from: "baseExtendInfo",
                    let: {
                        "accountid3": "$accountid2"
                    },
                    pipeline: [
                        {
                            $match: {
                                "$expr": {
                                    $and: [
                                        {
                                            $eq: [
                                                "$$accountid3",
                                                "$baseid"
                                            ]
                                        },

                                    ]
                                }
                            }
                        },
                        {
                            $project: {
                                "stuname": "$学生姓名",
                                "grade": "$年级",
                                "classno": "$班级",
                                "_id": 0
                            }
                        }
                    ],
                    as: "baseExtendInfo"
                }
            },
            {
                $match: {
                    "baseExtendInfo.classno": classno
                }
            },
            {
                $unwind: "$baseExtendInfo"
            },
            {
                $project: {
                    "status": {
                        $cond: {
                            if: { $eq: [ctx.state.noticeStatus.get("sign"), "$status"] },
                            then: "已签",
                            else: "未签"
                        }
                    },
                    "stuname": "$baseExtendInfo.stuname",
                    "grade": "$baseExtendInfo.grade",
                    "classno": "$baseExtendInfo.classno",
                    "sign":"$sign"
                }
            }
        ])
        ctx.body = { 'error': false, result: signstatus }
    } catch (err) {
        throw new Error("获取通知状态人员时出错:[" + err + "]")
    }
})

//按班级获取通知签收情况含签字图片
router.post('/getSignImageForStu', async (ctx, next) => {
    let noticeid = ctx.request.body.noticeid;
    let classno = ctx.request.body.classno;
    let pagesize=ctx.request.body.pagesize||9;
    let page=ctx.request.body.page||1;
    try {
        let signstatus = await noticeRece.countByAggregate([
            {
                $match: {
                    "status": ctx.state.noticeStatus.get("sign"),
                    "noticeid": noticeid
                }
            },
            {
                $addFields: {
                    accountid2: {
                        $toObjectId: "$accountid"
                    }
                }
            },
            {
                $lookup: {
                    from: "base",
                    localField: "accountid2",
                    foreignField: "_id",
                    as: "baseinfo"
                }
            },
            { $unwind: "$baseinfo" },
            { $match: { "baseinfo.classno": classno } },
            {
                $project: {
                    "stuname": "$baseinfo.username",
                    "grade": "$baseinfo.grade",
                    "classno": "$baseinfo.classno",
                    "sign": "$sign",
                    "_id": 1
                }
            },
            { $sort: { stuname: -1 } },
            { $skip: pagesize*(page-1) },
            { $limit: pagesize }
        ])
        ctx.body = { 'error': false, result: signstatus }
    } catch (err) {
        throw new Error("获取通知状态人员时出错:[" + err + "]")
    }
})
//获取用户未签字通知数量
router.get("/getUnSignNoticeCountByAccount",async (ctx,next)=>{
    let accountid = ctx.query.accountid;
    try {
        let unsigncount = await noticeRece.countByCondition({
            $and: [{
                "accountid": "61c73b5f75960624dcb182b0"
            }, {
                "status": {
                    $ne: ctx.state.noticeStatus.get("sign")
                }
            },{"fundesc":null}
        ]
        })
        ctx.body = { 'error': false, result: unsigncount }
    } catch (err) {
        throw new Error("获取用户未签字通知数量时出错:[" + err + "]")
    }
})

//根据ID获取通知内容
router.get('/getNoticeById/',async (ctx,next)=>{
    let id=ctx.query.id
    try{
        let res=await notice.GetOneByQuery({_id:id})
        ctx.body = { 'error': false, result: res }
    }catch(err){
        throw new Error("获取通知时出错:[" + err + "]")
    }
})

//保存新通知
router.post("/savenotice/",async (ctx,next)=>{
    let noticeinfo = ctx.request.body.noticeinfo;
    try{
        let res=notice.Save(noticeinfo)
        ctx.body={'error':false,result:res}
    }catch(err){
        throw new Error("保存通知时出错:["+err+"]")
    }
})
module.exports = router